package test.luin.pers.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WeatherActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView tv_city;
    private TextView tv_weather;
    private TextView tv_temp;
    private TextView tv_wind;
    private TextView tv_pm;
    private ImageView iv_icon;

    Map<String, WeatherInfor> weatherInforMap;
    List<WeatherInfor> list = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weather);
        init();

        InputStream is = this.getResources().openRawResource(R.raw.weather_json);
        try {
            list = WeatherServiceJSON.getInforFromJSON(is);
           weatherInforMap = new HashMap<>();
            for (WeatherInfor weatherInfor : list) {
                weatherInforMap.put(weatherInfor.getId(), weatherInfor);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        getMap("bj");
    }

    private void init() {
        tv_city = (TextView) findViewById(R.id.tv_city);
        tv_weather = (TextView) findViewById(R.id.tv_weather);
        tv_temp = (TextView) findViewById(R.id.tv_temp);
        tv_wind = (TextView) findViewById(R.id.tv_wind);
        tv_pm = (TextView) findViewById(R.id.tv_pm);
        iv_icon = (ImageView) findViewById(R.id.iv_icon);
        findViewById(R.id.btn_sh).setOnClickListener(this);
        findViewById(R.id.btn_bj).setOnClickListener(this);
        findViewById(R.id.btn_gz).setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_sh:
                getMap("sh");
                break;
            case R.id.btn_bj:
                getMap("bj");
                break;
            case R.id.btn_gz:
                getMap("gz");
                break;
        }
    }

    public void getMap(String id) {
        WeatherInfor wd = weatherInforMap.get(id);
        tv_city.setText(wd.getName());
        tv_weather.setText(wd.getWeather());
        tv_temp.setText(wd.getTemp());
        tv_wind.setText(wd.getWind());
        tv_pm.setText(wd.getPm());
        switch (wd.getWeather()) {
            case "晴天":
                iv_icon.setImageResource(R.drawable.sun);
                break;
            case "多云":
                iv_icon.setImageResource(R.drawable.clouds);
                break;
            case "晴天多云":
                iv_icon.setImageResource(R.drawable.cloud_sun);
                break;
        }
    }
}
